<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>用户主页 - 酒店管理系统</title>
    <link href="https://cdn.tailwindcss.com" rel="stylesheet" />
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
        }

        .section-box {
            background-color: #ffffff;
            border-radius: 0.5rem;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            transition: all 0.3s ease;
        }

        .hidden {
            display: none;
        }
    </style>
</head>

<body class="bg-gray-100 min-h-screen">

<!-- 页面顶部 -->
<div class="flex justify-between items-center bg-white shadow px-6 py-4 mb-6">
    <h1 class="text-2xl font-bold text-gray-800">用户主页</h1>
    <div class="text-sm text-gray-600">
        当前用户：
        <span id="loggedInUser" class="font-semibold text-indigo-600"></span>
    </div>
</div>

<!-- 主体容器 -->
<div class="container mx-auto px-4 space-y-6 max-w-3xl">

    <!-- 功能按钮 -->
    <div class="flex flex-wrap gap-4 justify-center">
        <button data-target="profile" class="btn-toggle px-5 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition duration-200">
            查看个人信息
        </button>
        <button data-target="recharge" class="btn-toggle px-5 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition duration-200">
            充值
        </button>
        <button data-target="orders" class="btn-toggle px-5 py-2 bg-purple-600 text-white rounded hover:bg-purple-700 transition duration-200">
            查看历史订单
        </button>
        <button data-target="wallet" class="btn-toggle px-5 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 transition duration-200">
            我的钱包
        </button>
        <button data-target="signIn" id="checkinButton" class="btn-toggle px-5 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition duration-200">
            签到
        </button>
        <button data-target="history" class="btn-toggle px-5 py-2 bg-pink-600 text-white rounded hover:bg-pink-700 transition duration-200">
            浏览历史
        </button>
        <button data-target="editProfile" class="btn-toggle px-5 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700 transition duration-200">
            修改个人信息
        </button>
        <button id="viewPointsInfoButton" class="btn-toggle px-5 py-2 bg-teal-600 text-white rounded hover:bg-teal-700 transition duration-200">
            查看积分信息
        </button>
        <button id="viewCheckinHistoryButton" class="btn-toggle px-5 py-2 bg-orange-600 text-white rounded hover:bg-orange-700 transition duration-200">
            查看历史签到信息
        </button>
        <button id="browseStoresButton" class="btn-toggle px-5 py-2 bg-cyan-600 text-white rounded hover:bg-cyan-700 transition duration-200">
            浏览店铺
        </button>
    </div>

    <!-- 各功能区域（默认隐藏） -->
    <div id="profile" class="hidden section-box">
        <h2 class="text-xl font-semibold mb-4">个人信息</h2>
        <div id="profileContent" class="space-y-2 text-gray-700"></div>
    </div>

    <div id="recharge" class="hidden section-box">
        <h2 class="text-xl font-semibold mb-4">充值</h2>
        <div class="space-y-4">
            <div>
                <label for="rechargeAmount" class="block text-sm font-medium text-gray-700">充值金额：</label>
                <input type="number" id="rechargeAmount" required class="w-full border border-gray-300 rounded px-3 py-2 mt-1" />
            </div>
            <div>
                <label for="rechargeReason" class="block text-sm font-medium text-gray-700">充值原因：</label>
                <input type="text" id="rechargeReason" required class="w-full border border-gray-300 rounded px-3 py-2 mt-1" />
            </div>
            <button id="submitRecharge" class="px-5 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition duration-200">
                提交充值申请
            </button>
        </div>
    </div>
    <div id="orders" class="hidden section-box"></div>
    <div id="wallet" class="hidden section-box">
        <h2 class="text-xl font-semibold mb-4">我的钱包</h2>
        <div id="walletContent" class="space-y-2 text-gray-700"></div>
        <button id="viewTransactionLogButton" class="px-5 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition duration-200 hidden">
            查看账单流水
        </button>
        <div id="transactionLogContent" class="space-y-2 text-gray-700 hidden"></div>
    </div>
    <div id="signIn" class="hidden section-box"></div>
    <div id="history" class="hidden section-box">
        <h2 class="text-xl font-semibold mb-4">浏览历史</h2>
        <div id="historyContent" class="space-y-2 text-gray-700"></div>
        <div id="noHistoryMessage" class="hidden">
            <p class="text-gray-500">暂无浏览历史记录</p>
        </div>
    </div>
    <div id="editProfile" class="hidden section-box"></div>
    <div id="pointsInfo" class="hidden section-box">
        <h2 class="text-xl font-semibold mb-4">积分信息</h2>
        <div id="pointsInfoContent" class="space-y-2 text-gray-700"></div>
    </div>
    <div id="checkinHistory" class="hidden section-box">
        <h2 class="text-xl font-semibold mb-4">历史签到信息</h2>
        <div id="checkinHistoryContent" class="space-y-2 text-gray-700"></div>
    </div>
</div>

<!-- 修改个人信息模态框 -->
<div id="editProfileModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50 p-4">
    <div class="bg-white w-full max-w-md p-6 rounded-lg shadow-lg">
        <h2 class="text-xl font-semibold mb-4">修改个人信息</h2>
        <form id="editProfileForm" class="space-y-4">
            <input type="hidden" id="userId" />

            <div>
                <label for="editUsername" class="block text-sm font-medium text-gray-700">用户名：</label>
                <input type="text" id="editUsername" required class="w-full border border-gray-300 rounded px-3 py-2 mt-1" />
            </div>

            <div>
                <label for="editPassword" class="block text-sm font-medium text-gray-700">新密码：</label>
                <input type="password" id="editPassword" class="w-full border border-gray-300 rounded px-3 py-2 mt-1" />
            </div>

            <div>
                <label for="editGender" class="block text-sm font-medium text-gray-700">性别：</label>
                <select id="editGender" required class="w-full border border-gray-300 rounded px-3 py-2 mt-1">
                    <option value="">请选择</option>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>

            <div>
                <label for="editAge" class="block text-sm font-medium text-gray-700">年龄：</label>
                <input type="number" id="editAge" required class="w-full border border-gray-300 rounded px-3 py-2 mt-1" />
                <div id="ageBirthdayWarning" class="text-red-500 text-sm mt-1 hidden">年龄与生日差距较大，建议重新确认</div>
            </div>

            <div>
                <label for="editBirthday" class="block text-sm font-medium text-gray-700">生日：</label>
                <input type="date" id="editBirthday" required class="w-full border border-gray-300 rounded px-3 py-2 mt-1" />
            </div>

            <div class="flex justify-end space-x-3 mt-6">
                <button type="button" id="cancelEditBtn" class="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400">
                    取消
                </button>
                <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700">
                    保存修改
                </button>
            </div>

        </form>
    </div>
</div>

<script>
    let currentUserData = null;
    document.addEventListener("DOMContentLoaded", function () {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        if (username) {
            document.getElementById("loggedInUser").textContent = username;
        } else {
            document.getElementById("loggedInUser").textContent = "当前用户信息获取失败";
        }

        // 页面加载时获取用户信息
        fetch(`/getUserInfo?username=${encodeURIComponent(username)}`)
    .then(response => response.json())
    .then(user => {
        if (user) {
            currentUserData = user;
            // 确保用户数据包含userId
            if (!user.userId) {
                alert("用户信息不完整，请重新登录");
                return;
            }
        } else {
            alert("无法加载用户信息");
        }
    })
           .catch(error => {
                console.error("获取用户信息失败:", error);
                alert("无法加载用户信息，请重试");
            });

        function showModal() {
            const editProfileModal = document.getElementById("editProfileModal");
            if (editProfileModal) {
                editProfileModal.classList.remove("hidden");
            }
        }

        function hideModal() {
            const editProfileModal = document.getElementById("editProfileModal");
            if (editProfileModal) {
                editProfileModal.classList.add("hidden");
            }
        }

        function showUserProfile(username) {
            fetch(`/getUserInfo?username=${encodeURIComponent(username)}`)
               .then(response => response.json())
               .then(user => {
                    const profileContent = document.getElementById("profileContent");
                    if (user) {
                        profileContent.innerHTML = `
                            <p><strong>用户名：</strong>${user.username}</p>
                            <p><strong>性别：</strong>${user.gender}</p>
                            <p><strong>年龄：</strong>${user.age}</p>
                            <p><strong>生日：</strong>${user.birthday.split('T')[0]}</p>
                            <p><strong>状态：</strong>${user.userStatus}</p>
                        `;
                    } else {
                        profileContent.innerHTML = "无法加载用户信息";
                    }
                })
               .catch(error => {
                    console.error("获取用户信息失败:", error);
                    alert("无法加载用户信息，请重试");
                });
        }

        function loadAndFillUserInfo() {
            fetch(`/getUserInfo?username=${encodeURIComponent(username)}`)
               .then(response => response.json())
               .then(user => {
                    if (user) {
                        currentUserData = user;
                        document.getElementById("userId").value = user.userId;
                        document.getElementById("editUsername").value = user.username;
                        document.getElementById("editPassword").value = "";
                        document.getElementById("editGender").value = user.gender;
                        document.getElementById("editAge").value = user.age;
                        // 确保日期格式正确
                        const birthday = new Date(user.birthday);
                        const formattedBirthday = `${birthday.getFullYear()}-${String(birthday.getMonth() + 1).padStart(2, '0')}-${String(birthday.getDate()).padStart(2, '0')}`;
                        document.getElementById("editBirthday").value = formattedBirthday;
                        showModal();
                    } else {
                        alert("无法加载用户信息");
                    }
                })
               .catch(error => {
                    console.error("获取用户信息失败:", error);
                    alert("无法加载用户信息，请重试");
                });
        }

        // 年龄与生日联动 + 提示
        function updateBirthdayFromAge() {
            const age = parseInt(document.getElementById("editAge").value);
            if (!isNaN(age)) {
                const birthYear = new Date().getFullYear() - age;
                document.getElementById("editBirthday").value = `${birthYear}-01-01`;
            }
        }

        function updateAgeFromBirthday() {
            const birthday = new Date(document.getElementById("editBirthday").value);
            const today = new Date();
            let age = today.getFullYear() - birthday.getFullYear();

            if (
                today.getMonth() < birthday.getMonth() ||
                (today.getMonth() === birthday.getMonth() && today.getDate() < birthday.getDate())
            ) {
                age--;
            }

            document.getElementById("editAge").value = age;

            // 显示警告
            const warning = document.getElementById("ageBirthdayWarning");
            if (Math.abs(parseInt(document.getElementById("editAge").value) - (new Date().getFullYear() - birthday.getFullYear())) > 2) {
                warning.classList.remove("hidden");
            } else {
                warning.classList.add("hidden");
            }
        }

        document.getElementById("editAge").addEventListener("input", updateAgeFromBirthday);
        document.getElementById("editBirthday").addEventListener("change", updateAgeFromBirthday);

        // 表单提交事件
        document.getElementById("editProfileForm").addEventListener("submit", function (e) {
            e.preventDefault();

            const userId = parseInt(document.getElementById("userId").value);
            const newUsername = document.getElementById("editUsername").value.trim();
            const newPassword = document.getElementById("editPassword").value.trim();
            const gender = document.getElementById("editGender").value;
            const age = parseInt(document.getElementById("editAge").value);
            const birthday = document.getElementById("editBirthday").value;

            const payload = {
                userId,
                username: newUsername,
                password: newPassword || undefined,
                gender,
                age,
                birthday
            };

            // 校验逻辑
            const today = new Date();
            const birthDate = new Date(birthday);

            if (birthDate > today) {
                alert("生日不能晚于当前时间");
                return;
            }

            const minBirthDate = new Date();
            minBirthDate.setFullYear(today.getFullYear() - 130);
            if (birthDate < minBirthDate) {
                alert(`出生年份不能早于 ${minBirthDate.getFullYear()}`);
                return;
            }

            // 提示年龄与生日不一致
            const calculatedAge = today.getFullYear() - birthDate.getFullYear();
            if (Math.abs(calculatedAge - age) > 2) {
                if (!confirm("年龄与生日差距较大，是否继续？")) {
                    return;
                }
            }

            // 发送请求
            fetch("/updateUserInfo", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(payload)
            })
               .then(response => {
                    if (!response.ok) {
                        throw new Error(`服务器返回错误: ${response.status}`);
                    }
                    return response.text();
                })
               .then(result => {
                    alert(result);
                    if (result.includes("成功")) {
                        hideModal();

                        // 更新页面顶部用户名
                        if (payload.username !== document.getElementById("loggedInUser").textContent) {
                            document.getElementById("loggedInUser").textContent = payload.username;
                        }
                    }
                })
               .catch(error => {
                    console.error("更新用户信息失败:", error);
                    alert("更新用户信息失败，请重试");
                });
        });

        // 取消编辑按钮事件
        document.getElementById("cancelEditBtn").addEventListener("click", hideModal);

        // 功能按钮点击事件
        document.querySelectorAll('.btn-toggle').forEach(button => {
            button.addEventListener('click', function () {
                const target = this.dataset.target;

                // 如果是查看个人信息，则调用单独函数
                if (target === 'profile') {
                    const username = document.getElementById("loggedInUser").textContent;
                    showUserProfile(username);
                }

                // 隐藏所有面板
                document.querySelectorAll('.section-box').forEach(box => {
                    box.classList.add('hidden');
                });

                // 显示目标面板
                const targetElement = document.getElementById(target);
                if (targetElement) {
                    targetElement.classList.remove('hidden');
                }

                // 如果是修改个人信息，加载数据并显示模态框
                if (target === 'editProfile') {
                    loadAndFillUserInfo();
                }

                // 如果是我的钱包，获取并显示钱包信息
                if (target === 'wallet') {
                    const userId = currentUserData ? currentUserData.userId : null;
                    if (!userId) {
                        alert("无法获取用户 ID，请重新登录或刷新页面");
                        return;
                    }

                    // 获取钱包信息
                    fetch(`/getUserWalletBalance?userId=${userId}`)
                       .then(response => {
                            if (!response.ok) {
                                throw new Error(`服务器返回错误: ${response.status}`);
                            }
                            return response.json();
                        })
                       .then(walletBalance => {
                            const walletContent = document.getElementById("walletContent");
                            if (walletBalance) {
                                walletContent.innerHTML = `
                                    <p><strong>总金额：</strong>${walletBalance.totalAmount}</p>
                                    <p><strong>充值金额：</strong>${walletBalance.rechargeAmount}</p>
                                    <p><strong>消费金额：</strong>${walletBalance.consumptionAmount}</p>
                                `;
                                document.getElementById("viewTransactionLogButton").classList.remove("hidden");
                            } else {
                                walletContent.innerHTML = "暂无钱包信息";
                            }
                        })
                       .catch(error => {
                            console.error("获取钱包信息失败:", error);
                            alert("获取钱包信息失败，请重试");
                        });
                }

                // 如果是查看历史订单
                if (target === 'orders') {
                    const userId = currentUserData ? currentUserData.userId : null;
                    if (!userId) {
                        alert("无法获取用户 ID，请重新登录或刷新页面");
                        return;
                    }

                    // 隐藏所有面板
                    document.querySelectorAll('.section-box').forEach(box => {
                        box.classList.add('hidden');
                    });

                    // 显示历史订单面板
                    const ordersSection = document.getElementById("orders");
                    if (ordersSection) {
                        ordersSection.classList.remove('hidden');
                    }

                    // 获取历史订单信息
                    fetch(`/getUserHistoryOrders?userId=${userId}`)
                       .then(response => {
                            if (!response.ok) {
                                throw new Error(`服务器返回错误: ${response.status}`);
                            }
                            return response.json();
                        })
                       .then(orders => {
                            const ordersContent = document.createElement('div');
                            if (orders.length > 0) {
                                let html = '<h2 class="text-xl font-semibold mb-4">历史订单信息</h2>';
                                orders.forEach(order => {
                                    html += `
                                        <div class="border p-4 mb-4" data-order-id="${order.orderId}">
                                            <p><strong>商家名称：</strong>${order.merchantName}</p>
                                            <p><strong>联系电话：</strong>${order.contactPhone}</p>
                                            <p><strong>总消费金额：</strong>${order.totalConsumption}</p>
                                            <p><strong>床型：</strong>${order.bedType}</p>
                                            <p><strong>房间数量：</strong>${order.roomTypeQuantity}</p>
                                            <p><strong>下单时间：</strong>${order.orderPlacementTime}</p>
                                            <p><strong>入住时间：</strong>${order.checkInTime}</p>
                                            <p><strong>退房时间：</strong>${order.checkOutTime}</p>
                                            <p><strong>订单状态：</strong>${order.orderStatus}</p>
                                            <p><strong>备注：</strong>${order.remarks}</p>
                                            <div class="mt-4">
                                                <button class="px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 mr-2 apply-checkin" data-order-id="${order.orderId}">入住</button>
                                                <button class="px-3 py-1 bg-yellow-600 text-white rounded hover:bg-yellow-700 mr-2">退房</button>
                                                <button class="px-3 py-1 bg-red-600 text-white rounded hover:bg-red-700">退款</button>
                                            </div>
                                        </div>
                                    `;
                                });
                                ordersContent.innerHTML = html;
                            } else {
                                ordersContent.innerHTML = "<p>暂无历史订单信息</p>";
                            }
                            ordersSection.innerHTML = '';
                            ordersSection.appendChild(ordersContent);


                            // 为“入住”按钮添加点击事件绑定
                            document.querySelectorAll('.apply-checkin').forEach(button => {
                                button.addEventListener('click', function () {
                                    const orderId = this.dataset.orderId;
                                    applyCheckIn(orderId);
                                });
                            });
                            // 为“退房”按钮添加点击事件绑定
                            bindCheckOutButtons();
                            // 绑定退款按钮事件
                            bindRefundButtons();

                        })
                       .catch(error => {
                            console.error("获取历史订单信息失败:", error);
                            alert("获取历史订单信息失败，请重试");
                        });
                }
            });
        });

        // 签到按钮点击事件
        document.getElementById("checkinButton").addEventListener("click", function () {
            // 确保 currentUserData 存在且 userId 有效
            if (!currentUserData ||!currentUserData.userId) {
                alert("用户信息获取异常，请重新登录或刷新页面");
                return;
            }
            const userId = currentUserData.userId;
            const pointsEarned = 10; // 假设每次签到获得 10 积分

            const formData = new URLSearchParams();
            formData.append('userId', userId);
            formData.append('pointsEarned', pointsEarned);

            // 发送签到请求
            fetch("/checkin", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: formData.toString()
            })
               .then(response => {
                    if (!response.ok) {
                        throw new Error(`服务器返回错误: ${response.status}`);
                    }
                    return response.text();
                })
               .then(result => {
                    alert(result);
                    // 可以考虑更新积分信息
                    if (result.includes("签到成功")) {
                        document.getElementById("viewPointsInfoButton").click();
                    }
                })
               .catch(error => {
                    console.error("签到失败:", error);
                    alert("签到失败，请重试");
                });
        });

        document.getElementById("browseStoresButton").addEventListener("click", function () {
            const username = document.getElementById("loggedInUser").textContent;
            // 将用户名作为参数添加到跳转的 URL 中
            window.location.href = `store-page.html?username=${encodeURIComponent(username)}`;
        });

        // 查看积分信息按钮点击事件
        document.getElementById("viewPointsInfoButton").addEventListener("click", function () {
            const userId = currentUserData ? currentUserData.userId : null;
            if (!userId) {
                alert("无法获取用户 ID，请重新登录或刷新页面");
                return;
            }

            // 隐藏所有面板
            document.querySelectorAll('.section-box').forEach(box => {
                box.classList.add('hidden');
            });

            // 显示积分信息面板
            const pointsInfo = document.getElementById("pointsInfo");
            if (pointsInfo) {
                pointsInfo.classList.remove('hidden');
            }

            // 获取积分信息
            fetch(`/getPointsInfo?userId=${userId}`)
               .then(response => {
                    if (!response.ok) {
                        throw new Error(`服务器返回错误: ${response.status}`);
                    }
                    return response.json();
                })
               .then(pointsInfo => {
                    const pointsInfoContent = document.getElementById("pointsInfoContent");
                    if (Object.keys(pointsInfo).length > 0) {
                        pointsInfoContent.innerHTML = `
                            <p><strong>总积分：</strong>${pointsInfo.totalPoints}</p>
                            <p><strong>连续签到天数：</strong>${pointsInfo.consecutiveDays}</p>
                            <p><strong>累计签到天数：</strong>${pointsInfo.cumulativeDays}</p>
                        `;
                    } else {
                        pointsInfoContent.innerHTML = "暂无积分信息";
                    }
                })
               .catch(error => {
                    console.error("获取积分信息失败:", error);
                    alert("获取积分信息失败，请重试");
                });
        });

        // 查看历史签到信息按钮点击事件
        document.getElementById("viewCheckinHistoryButton").addEventListener("click", function () {
            const userId = currentUserData ? currentUserData.userId : null;
            if (!userId) {
                alert("无法获取用户 ID，请重新登录或刷新页面");
                return;
            }

            // 隐藏所有面板
            document.querySelectorAll('.section-box').forEach(box => {
                box.classList.add('hidden');
            });

            // 显示历史签到信息面板
            const checkinHistory = document.getElementById("checkinHistory");
            if (checkinHistory) {
                checkinHistory.classList.remove('hidden');
            }

            // 获取历史签到信息
            fetch(`/getCheckinHistory?userId=${userId}`)
               .then(response => {
                    if (!response.ok) {
                        throw new Error(`服务器返回错误: ${response.status}`);
                    }
                    return response.json();
                })
               .then(checkinHistory => {
                    const checkinHistoryContent = document.getElementById("checkinHistoryContent");
                    if (checkinHistory.length > 0) {
                        let html = '';
                        checkinHistory.forEach(checkin => {
                            html += `
                                <p><strong>签到时间：</strong>${checkin.checkinTime}</p>
                                <p><strong>获得积分：</strong>${checkin.pointsEarned}</p>
                                <hr class="my-2">
                            `;
                        });
                        checkinHistoryContent.innerHTML = html;
                    } else {
                        checkinHistoryContent.innerHTML = "暂无历史签到信息";
                    }
                })
               .catch(error => {
                    console.error("获取历史签到信息失败:", error);
                    alert("获取历史签到信息失败，请重试");
                });
        });

        // 充值按钮点击事件
        document.getElementById("submitRecharge").addEventListener("click", async function () {
            const userId = currentUserData ? currentUserData.userId : null;
            if (!userId) {
                alert("无法获取用户 ID，请重新登录或刷新页面");
                return;
            }

            const topUpAmount = document.getElementById("rechargeAmount").value;
            const rechargeReason = document.getElementById("rechargeReason").value;
            // 简单的输入验证，确保充值金额为正数
            if (isNaN(topUpAmount) || parseFloat(topUpAmount) <= 0) {
                alert("请输入有效的正数作为充值金额！");
                return;
            }
            const rechargeAuditStatus = "审核中";
            const formData = new URLSearchParams();
            formData.append('userId', userId);
            formData.append('topUpAmount', topUpAmount);
            formData.append('rechargeAuditStatus', rechargeAuditStatus);
            formData.append('rechargeReason', rechargeReason);

            try {
                const response = await fetch("/submitRecharge", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: formData.toString()
                });
                const result = await response.text();

                if (result.includes("您上条充值仍在审核中")) {
                    const confirmResult = confirm(result);
                    if (confirmResult) {
                        formData.append('confirmContinue', 'true');
                        const confirmResponse = await fetch("/submitRecharge", {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded"
                            },
                            body: formData.toString()
                        });
                        const confirmResultText = await confirmResponse.text();

                        if (confirmResultText.includes("成功")) {
                            alert("充值信息已提交，请等待管理员审核");
                            // 可以考虑更新页面上的钱包信息显示
                        }
                    }
                } else {

                    if (result.includes("成功")) {
                        alert("充值信息已提交，请等待管理员审核");
                        // 可以考虑更新页面上的钱包信息显示
                    }
                }
            } catch (error) {
                console.error("更新用户钱包信息失败:", error);
                alert("更新用户钱包信息失败，请重试");
            }
        });

        // 查看账单流水按钮点击事件
        document.getElementById("viewTransactionLogButton").addEventListener("click", function () {
            const userId = currentUserData ? currentUserData.userId : null;
            if (!userId) {
                alert("无法获取用户 ID，请重新登录或刷新页面");
                return;
            }

            // 获取账单流水信息
            fetch(`/getWalletTransactionLog?userId=${userId}`)
               .then(response => {
                    if (!response.ok) {
                        throw new Error(`服务器返回错误: ${response.status}`);
                    }
                    return response.json();
                })
               .then(transactionLog => {
                    const transactionLogContent = document.getElementById("transactionLogContent");
                    if (transactionLog.length > 0) {
                        let html = '';
                        transactionLog.forEach(log => {
                            html += `
                                <p><strong>交易时间：</strong>${log.transactionTime}</p>
                                <p><strong>交易类型：</strong>${log.transactionType}</p>
                                <p><strong>交易金额：</strong>${log.transactionAmount}</p>
                                <hr class="my-2">
                            `;
                        });
                        transactionLogContent.innerHTML = html;
                    } else {
                        transactionLogContent.innerHTML = "暂无账单流水信息";
                    }
                    transactionLogContent.classList.remove("hidden");
                })
               .catch(error => {
                    console.error("获取账单流水信息失败:", error);
                    alert("获取账单流水信息失败，请重试");
                });
        });
    });

    function applyCheckIn(orderId) {
    if (!currentUserData) {
        alert("用户信息正在加载，请稍候再试");
        return;
    }
    const userId = currentUserData.userId;
    const formData = new URLSearchParams();
    formData.append('orderId', orderId);
    formData.append('userId', userId);

    fetch("/applyCheckIn", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: formData.toString()
    })
   .then(response => {
        if (!response.ok) {
            throw new Error(`服务器返回错误: ${response.status}`);
        }
        return response.text();
    })
   .then(result => {
        if (result.includes("成功")) {
            alert("正在申请入住，请等待商家核销");
            const orderDiv = document.querySelector(`[data-order-id="${orderId}"]`);
            if (orderDiv) {
                let statusElement;
                const paragraphs = orderDiv.getElementsByTagName('p');
                for (let i = 0; i < paragraphs.length; i++) {
                    const strongElements = paragraphs[i].getElementsByTagName('strong');
                    for (let j = 0; j < strongElements.length; j++) {
                        if (strongElements[j].textContent.includes("订单状态")) {
                            statusElement = strongElements[j];
                            break;
                        }
                    }
                    if (statusElement) {
                        break;
                    }
                }
                if (statusElement) {
                    statusElement.textContent = "订单状态：申请中";
                }
            }
        } else {
            alert(result);
        }
    })
   .catch(error => {
        console.error("申请入住失败:", error);
        alert("申请入住失败，请重试");
    });
}

    // 退房功能实现
function checkOut(orderId) {
    if (!currentUserData) {
        alert("用户信息正在加载，请稍候再试");
        return;
    }

    // 确认对话框
    if (!confirm("确定要办理退房吗？")) {
        return;
    }

    const userId = currentUserData.userId;
    const formData = new URLSearchParams();
    formData.append('orderId', orderId);
    formData.append('userId', userId);

    fetch("/checkOut", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: formData.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`服务器返回错误: ${response.status}`);
        }
        return response.text();
    })
    .then(result => {
        if (result.includes("成功")) {
            alert("退房成功，订单已完成");
            // 更新UI显示
            const orderDiv = document.querySelector(`[data-order-id="${orderId}"]`);
            if (orderDiv) {
                // 查找订单状态元素
                const statusElement = Array.from(orderDiv.querySelectorAll('p')).find(p =>
                    p.textContent.includes('订单状态')
                )?.querySelector('strong');

                if (statusElement) {
                    statusElement.textContent = "订单状态：已完成";
                }

                const buttons = orderDiv.querySelectorAll('button');
            for (const button of buttons) {
                if (button.textContent.trim() === "退房") {
                    button.disabled = true;
                    button.classList.add('bg-gray-400', 'cursor-not-allowed');
                    button.classList.remove('bg-yellow-600', 'hover:bg-yellow-700');
                    break;

            }
            }
            }
        } else {
            alert(result);
        }
    })
    .catch(error => {
        console.error("退房失败:", error);
        alert("退房失败，请重试");
    });
}

    // 绑定退房按钮事件（独立函数）
    function bindCheckOutButtons() {
    const ordersSection = document.getElementById('orders');
    if (!ordersSection) return;
    const buttons = ordersSection.querySelectorAll('button');
    buttons.forEach(button => {
        if (button.textContent.trim() === '退房') {
            button.addEventListener('click', function() {
                const orderId = this.closest('[data-order-id]')?.dataset.orderId;
                if (orderId) {
                    checkOut(orderId);
                }
            });
        }
    });
}

    // 更新退房后的UI显示
    function updateCheckOutUI(orderId) {
        const orderDiv = document.querySelector(`[data-order-id="${orderId}"]`);
        if (!orderDiv) return;

        // 查找并更新订单状态
        const statusElements = orderDiv.querySelectorAll('p');
        for (const element of statusElements) {
            if (element.textContent.includes('订单状态')) {
                const statusText = element.querySelector('strong');
                if (statusText) {
                    statusText.textContent = "订单状态：已完成";
                }
                break;
            }
        }

    // 查找并禁用退房按钮
        const buttons = orderDiv.querySelectorAll('button');
        for (const button of buttons) {
            if (button.textContent.trim() === "退房") {
                button.disabled = true;
                button.classList.add('bg-gray-400', 'cursor-not-allowed');
                button.classList.remove('bg-yellow-600', 'hover:bg-yellow-700');
                break;
            }
        }
    }

    // 退款功能实现
function refundOrder(orderId) {
    if (!currentUserData) {
        alert("用户信息正在加载，请稍候再试");
        return;
    }

    // 获取订单状态
    const orderDiv = document.querySelector(`[data-order-id="${orderId}"]`);
    if (!orderDiv) {
        alert("订单信息不存在，请刷新页面后重试");
        return;
    }

    // 提取当前订单状态
    let currentStatus = "";
    const statusElement = Array.from(orderDiv.querySelectorAll('p')).find(p =>
        p.textContent.includes('订单状态')
    );

    if (statusElement) {
        currentStatus = statusElement.textContent.split('：')[1].trim();
    } else {
        alert("无法获取订单状态，请刷新页面后重试");
        return;
    }

    // 检查订单状态是否允许退款
    if (currentStatus !== "正常" && currentStatus !== "申请中") {
        alert("只有状态为正常或申请中的订单可以退款");
        return;
    }

    // 确认对话框
    if (!confirm("确定要申请退款吗？")) {
        return;
    }

    const userId = currentUserData.userId;
    const formData = new URLSearchParams();
    formData.append('orderId', orderId);
    formData.append('userId', userId);

    fetch("/refundOrder", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: formData.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`服务器返回错误: ${response.status}`);
        }
        return response.text();
    })
    .then(result => {
        if (result.includes("成功")) {
            alert("退款申请已提交，请等待商家处理");
            // 更新UI显示
            const orderDiv = document.querySelector(`[data-order-id="${orderId}"]`);
            if (orderDiv) {
                // 查找订单状态元素
                const statusElement = Array.from(orderDiv.querySelectorAll('p')).find(p =>
                    p.textContent.includes('订单状态')
                )?.querySelector('strong');

                if (statusElement) {
                    statusElement.textContent = "订单状态：退款中";
                }

                // 禁用退款按钮
                const buttons = orderDiv.querySelectorAll('button');
                for (const button of buttons) {
                    if (button.textContent.trim() === "退款") {
                        button.disabled = true;
                        button.classList.add('bg-gray-400', 'cursor-not-allowed');
                        button.classList.remove('bg-red-600', 'hover:bg-red-700');
                        break;
                    }
                }
            }
        } else {
            alert(result);
        }
    })
    .catch(error => {
        console.error("退款失败:", error);
        alert("退款失败，请重试");
    });
}

// 绑定退款按钮事件
function bindRefundButtons() {
    const ordersSection = document.getElementById('orders');
    if (!ordersSection) return;

    const buttons = ordersSection.querySelectorAll('button');
    buttons.forEach(button => {
        if (button.textContent.trim() === '退款') {
            button.addEventListener('click', function() {
                const orderId = this.closest('[data-order-id]')?.dataset.orderId;
                if (orderId) {
                    refundOrder(orderId);
                }
            });
        }
    });
}
    // 在DOMContentLoaded事件处理函数中添加以下代码
document.getElementById("browseStoresButton").addEventListener("click", function () {
    const username = document.getElementById("loggedInUser").textContent;
    // 将用户名作为参数添加到跳转的URL中
    window.location.href = `store-page.html?username=${encodeURIComponent(username)}`;
});

// 添加浏览历史按钮事件处理
document.querySelector('button[data-target="history"]').addEventListener("click", function() {
    // 隐藏所有面板
    document.querySelectorAll('.section-box').forEach(box => {
        box.classList.add('hidden');
    });

    // 显示浏览历史面板
    const historySection = document.getElementById("history");
    if (historySection) {
        historySection.classList.remove('hidden');
    }

    // 获取当前用户ID
    const userId = currentUserData ? currentUserData.userId : null;
    if (!userId) {
        alert("无法获取用户ID，请重新登录或刷新页面");
        return;
    }

    // 显示加载中状态
    document.getElementById("historyContent").innerHTML = "<p class=\"text-gray-500\">加载中...</p>";
    document.getElementById("noHistoryMessage").classList.add("hidden");

    // 发送请求获取浏览历史
    fetch(`/getBrowsingHistory?userId=${userId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器返回错误: ${response.status}`);
            }
            return response.json();
        })
        .then(historyList => {
            const historyContent = document.getElementById("historyContent");

            if (historyList && historyList.length > 0) {
                // 有浏览历史记录，生成HTML
                let html = '';
                historyList.forEach(history => {
                    // 格式化浏览时间
                    const browsingTime = new Date(history.browsingTime).toLocaleString();

                    html += `
                        <div class="border-b pb-3 mb-3 last:border-b-0 last:mb-0 last:pb-0">
                            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-2">
                                <div>
                                    <p class="font-medium text-gray-800">${history.merchantName}</p>
                                    <p class="text-sm text-gray-500">商家ID: ${history.merchantId}</p>
                                </div>
                                <p class="text-sm text-gray-500">${browsingTime}</p>
                            </div>
                        </div>
                    `;
                });
                historyContent.innerHTML = html;
            } else {
                // 没有浏览历史记录
                historyContent.innerHTML = "";
                document.getElementById("noHistoryMessage").classList.remove("hidden");
            }
        })
        .catch(error => {
            console.error("获取浏览历史失败:", error);
            document.getElementById("historyContent").innerHTML = `<p class="text-red-500">获取浏览历史失败: ${error.message}</p>`;
        });
});


</script>

</body>

</html>